import request from "@/utils/request";
import { AxiosPromise } from "axios";
import { FileInfo, FileTreeList } from "./types";
import { UploadFile } from "element-plus";

/**
 * 文件上传
 *
 * @param file 文件对象
 * @returns 文件信息
 */
export function uploadFileApi(file: File): AxiosPromise<FileInfo> {
  const formData = new FormData();
  formData.append("file", file);
  return request({
    url: "/api/v1/files",
    method: "post",
    data: formData,
    headers: {
      "Content-Type": "multipart/form-data",
    },
  });
}

/**
 * 头像上传
 *
 * @param file 文件对象
 * @param fileName 文件名
 * @returns 文件信息
 */
export function uploadAvatarApi(
  blob: any,
  fileName: string
): AxiosPromise<FileInfo> {
  const formData = new FormData();
  formData.append("file", blob, fileName);
  return request({
    url: "/api/v1/files/avatar",
    method: "post",
    data: formData,
    headers: {
      "Content-Type": "multipart/form-data",
    },
  });
}

/**
 * 获取 Minio 下的所有文件
 *
 * @returns 文件列表
 */
export function fetchMinioFileListApi(): AxiosPromise<FileTreeList[]> {
  return request({
    url: "/api/v1/files/list",
    method: "get",
  });
}

/**
 * 根据文件名删除 Minio 下的文件
 *
 * @param fileName 文件名
 * @returns void
 */
export function deleteMinioFileApi(fileName: string) {
  return request({
    url: "/api/v1/files/delete",
    method: "delete",
    params: { fileName },
  });
}

/**
 * 批量删除文件
 * @param fileNames 文件名列表，多个文件名用逗号隔开，例如：file1,file2,file3
 * @returns void
 */
export function deleteFilesApi(fileNames: string[]) {
  return request({
    url: "/api/v1/files/deleteFiles",
    method: "delete",
    data: fileNames,
  });
}

/**
 * 文件下载
 * @param fileName 文件名
 * @returns 下载文件的响应流
 */
export function downloadMinioFileApi(fileName: string) {
  return request({
    url: `/api/v1/files/downLoadFile`,
    method: "get",
    params: { fileName },
    responseType: "blob", // 告诉axios返回的是blob类型的数据，用于下载文件
  });
}

/**
 * 批量文件上传 API
 * @param files 上传的文件列表
 */
export function uploadFilesApi(files: UploadFile[]) {
  const formData = new FormData();
  for (let file of files) {
    formData.append("files", file.raw!, file.name);
  }
  return request({
    url: "/api/v1/files/uploadFiles",
    method: "post",
    data: formData,
    headers: {
      "Content-Type": "multipart/form-data",
    },
  });
}

export function downLoadZipApi(fileNames: string[]) {
  return request({
    url: "/api/v1/files/downLoadZip",
    method: "post",
    data: fileNames,
    responseType: "blob",
  });
}
